package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 * ctrl+f12
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavors(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    //菜品信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //1). 构造分页条件对象
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();
        //SELECT * FROM dish WHERE NAME LIKE '%xx%' ORDER BY update_time DESC LIMIT 0 ,10
        //2). 构建查询及排序条件
        LambdaQueryWrapper<Dish> lwq=new LambdaQueryWrapper();
        lwq.like(name!=null,Dish::getName,name); //WHERE NAME LIKE '%xx%'
        lwq.orderByDesc(Dish::getUpdateTime);//ORDER BY update_time DESC
        //3). 执行分页条件查询
        dishService.page(pageInfo,lwq);


        //对象拷贝  将pageInfo对象上所有的属性赋值到dishDtoPage对象上,但是不包括records属性
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        //4). 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        List<Dish> records = pageInfo.getRecords();
        //设置一个集合,存入各个dishDto对象
        List<DishDto> records2=new ArrayList<>();
        for (Dish dish : records) {

            //创建DishDto对象,拷贝属性
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //根据dishDto的菜品分类ID查询菜品分类对象,设置分类名称
            Category category =categoryService.getById(dish.getCategoryId());
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
            //将dishDto存入集合中
            records2.add(dishDto);
        }
        //将集合设置到dishDtoPage对象上
        dishDtoPage.setRecords(records2);

        //5). 封装数据并返回
        //return R.success(pageInfo);
        return R.success(dishDtoPage); //dishDtoPage:total records[dishDto[dish,categoryName]]
    }


    //根据菜品ID查询菜品信息以及对应的口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto=dishService.getByIDWithFlavor(id);
        return R.success(dishDto);
    }


    //修改菜品以及口味
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavors(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品信息成功");
    }

    //根据菜品分类ID查询分类下所有的菜品信息
    //http://localhost:8080/dish/list?categoryId=1397844391040167938
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //# 查询川菜下的所有菜品
        //SELECT * FROM dish WHERE category_id='1397844303408574465' AND STATUS=1 order by sort asc, update_time desc
        //构造查询条件
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        //添加条件，查询状态为1（起售状态）的菜品
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId()); // WHERE category_id='1397844303408574465'
        lqw.eq(Dish::getStatus,1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询,返回集合
        List<Dish> list=dishService.list(lqw);
        return R.success(list);
    }*/


    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //直接获取redis中缓存的菜品信息
        List<DishDto> list02=null;
        //动态的构建key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();//dish_1342142134243243_1
        //从redis 中获取数据
        list02=(List<DishDto>)redisTemplate.opsForValue().get(key);

        if(list02!=null){
            //如果存在,直接返回,不需要查看数据
            return R.success(list02);
        }

        //# 查询川菜下的所有菜品
        //SELECT * FROM dish WHERE category_id='1397844303408574465' AND STATUS=1 order by sort asc, update_time desc
        //构造查询条件
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        //添加条件，查询状态为1（起售状态）的菜品
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId()); // WHERE category_id='1397844303408574465'
        lqw.eq(Dish::getStatus,1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询,返回集合
        List<Dish> list=dishService.list(lqw);

        list02=new ArrayList<>();
        //创建集合,存放的是DishDto
        for (Dish ds : list) {
            //创建DishDto
            DishDto dishDto=new DishDto();
            //将ds所有属性复制到DishDto
            BeanUtils.copyProperties(ds,dishDto);
            //根据ds查询ds对应的口味信息
            Long dishId=ds.getId();
             //根据dishId查询口味  SELECT * FROM dish_flavor WHERE dish_id='1397849739276890114'
            LambdaQueryWrapper<DishFlavor> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list1 = dishFlavorService.list(lqw2);
            //键改口味设置到DishDto
            dishDto.setFlavors(list1);
            list02.add(dishDto);
        }
        //将查询到的菜品存入到reids
        redisTemplate.opsForValue().set(key,list02,60, TimeUnit.MINUTES);
        return R.success(list02);
    }


}  